<!-- 表达编辑记录 -->
<template>
  <div class="box">
    <template v-if="!iframeHeight">
      <a-skeleton :animation="true">
        <a-space direction="vertical" :style="{ width: '100%' }" size="large">
          <a-skeleton-line :rows="3" />
          <a-skeleton-shape />
        </a-space>
      </a-skeleton>
    </template>
    <iframe
      v-if="iframeSrc"
      ref="iframeRef"
      :src="iframeSrc"
      allowfullscreen="true"
      webkitallowfullscreen="true"
      mozallowfullscreen="true"
      frameborder="0"
      width="100%"
      :height="iframeHeight"
      scrolling="no"
    ></iframe>

    <!-- 人员弹窗 -->
    <OrganChooseBox
      v-if="showChooseOrgan"
      v-model:visible="showChooseOrgan"
      v-model:selected="selectedIds"
      v-model:multiple="isMultiple"
      :hidden-dept="true"
      :hidden-role="true"
      @close="onCloseClick"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from "vue";
import { Notification } from "@arco-design/web-vue";
import { getToken } from "@/utils/auth";
import ObjectUtil from "@/components/flow/common/ObjectUtil";
import OrganChooseBox from "@/components/flow/dialog/OrganChooseBox.vue";
import OrganApi from "@/api/OrganApi";
import { useRouter, useRoute } from "vue-router";
const route = useRoute();

const props = defineProps({
  visible: { type: Boolean, default: false },
  flowInstId: { type: String },
  formId: { type: String, default: "" },
  modelId: { type: String, default: "" },
  model: { type: Object, default: {} },
});
const emits = defineEmits(["update:visible", "getForm"]);

const base_url = "http://203.33.215.198:9081/#/builder";
// const base_url = "http://192.168.110.148:5175/#/builder";
const iframeSrc = ref("");
const iframeRef = ref();
const iframeHeight = ref(0);

watch(
  () => props.flowInstId,
  (nv) => {
    if (nv) {
      const token = route.query.token ? route.query.token : getToken();
      iframeHeight.value = 0;
      iframeSrc.value = "";
      nextTick(() => {
        iframeSrc.value = `${base_url}?flowId=${nv}&token=${encodeURIComponent(
          token
        )}`;
      });
    }
  },
  { immediate: true }
);

watch(
  () => props.model.formId,
  (nv) => {
    if (nv) {
      const token = route.query.token ? route.query.token : getToken();
      iframeHeight.value = 0;
      iframeSrc.value = "";
      nextTick(() => {
        iframeSrc.value = `${base_url}?formId=${nv}&version=${
          props.model.formVersion
        }&modelId=${
          props.model.modelId
        }&nodetype='START_ENV'&token=${encodeURIComponent(token)}`;
      });
    }
  },
  { immediate: true, deep: true }
);

const setIframeHeight = (height) => {
  if (iframeRef.value) {
    iframeHeight.value = height;
  }
};

// 打开弹窗选择指定成员
let showChooseOrgan = ref(false); // 是否显示指定成员对话框
let isMultiple = ref(true); // 是否多选
let selectedIds = ref([]); // 当前选中人设置
let selectedField = ref("");
const onOpenClick = (params) => {
  console.log("onOpenClick", params);
  selectedIds.value = params.userIds || [];
  isMultiple.value = params.multiple;
  const field = params.field;
  selectedField.value = field;
  showChooseOrgan.value = true;
};
const onCloseClick = (data) => {
  console.log("onCloseClick", data);
  sendIframeData("user", selectedField.value, data);
};

// 接收iframe消息
const handleMessage = (event) => {
  console.log("handleMessage", event);
  if (ObjectUtil.isObject(event.data)) {
    return;
  }
  // 根据上面制定的结构来解析iframe内部发回来的数据
  const data = JSON.parse(event.data);
  const { cwd, formData, height, params } = data;
  console.log(data);
  // 表单数据
  if (cwd == "sendData") {
    if (!formData.data) {
      Notification.warning(`未获取到表单数据`);
      return;
    }
    emits("getForm", formData);
  }
  // 设置高度
  if (cwd == "sendHeight") {
    setIframeHeight(height);
  }
  // 打开弹窗
  if (cwd == "open") {
    onOpenClick(params);
  }
};

// iframe 传递消息给子组件
const sendIframeData = (flag, field = "", list = []) => {
  if (iframeRef.value) {
    console.log("给子级发送了消息");
    iframeRef.value.contentWindow.postMessage(
      JSON.stringify({
        cwd: flag,
        params: { users: list, field },
      }),
      "*"
    );
  }
};

onBeforeUnmount(() => {
  OrganApi.loadOrgan();
  window.removeEventListener("message", handleMessage);
});

onMounted(async () => {
  // 在外部vue的window上添加postMessage的监听，并且绑定处理函数handleMessage
  window.addEventListener("message", handleMessage);
});

const handleOk = () => {
  emits("update:visible", false);
};

defineExpose({ sendIframeData });
</script>

<style lang="less">
.box {
}
</style>
